package org.gap.wizards.utils;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.io.BufferedWriter;
import java.io.IOException;

public class ValuesPersistence {
	private static final int WIDTH = 0;
	private static final int HEIGHT = 1;
	
	private static final int X = 0;
	private static final int Y = 1;
	
	private static final int REC_X = 0;
	private static final int REC_Y = 1;
	private static final int REC_WIDTH = 2;
	private static final int REC_HEIGHT = 3;

	public static void writeRectangle(BufferedWriter writer, Rectangle rectangle) throws IOException {
		writer.write(rectangle.x + "," + rectangle.y + "," + rectangle.width + "," + rectangle.height);
	}
	
	public static Rectangle readRectangle(String data) {
		String[] values = data.split(",");
		int x = readInt(values[REC_X]);
		int y = readInt(values[REC_Y]);
		int width = readInt(values[REC_WIDTH]);
		int height = readInt(values[REC_HEIGHT]);
		return new Rectangle(x, y, width, height);
	}

	public static int readInt(String value) {
		return Integer.parseInt(value);
	}

	public static void writePoint(BufferedWriter writer, Point point) throws IOException {
		writer.write(point.x + "," + point.y);
	}

	public static Point readPoint(String data) {
		String[] values = data.split(",");
		int x = readInt(values[X]);
		int y = readInt(values[Y]);
		return new Point(x, y);
	}

	public static Dimension readDimensions(String data) {
		String[] dimensionData = data.split(",");
		int width = readInt(dimensionData[WIDTH]);
		int height = Integer.parseInt(dimensionData[HEIGHT]);
		return new Dimension(width, height);
	}
	
	public static void writeDimensions(BufferedWriter writer, Dimension dimensions) throws IOException {
		writer.write(dimensions.width + "," + dimensions.height);
	}

	public static Object readClass(String klass) {
		try {
			return Class.forName(klass).newInstance();
		} catch (InstantiationException e) {
			new RuntimeException("Unable to instantiate Item: " + klass);
		} catch (IllegalAccessException e) {
			// shouldn't ever happen.
		} catch (ClassNotFoundException e) {
			// Shouldn't ever happen
		}
		throw new RuntimeException("Should never get here: Instantiating [" + klass + "]");
	}
}
